<template>
  <div class="app-container" id="print">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编码" prop="billcode">
        <el-input
          v-model="queryParams.billcode"
          placeholder="请输入单据编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="billdate">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.billdate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择单据日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="区域" prop="areaid">
        <el-select
          v-model="queryParams.areaid"
          placeholder="请选择区域"
          clearable
          size="small"
        >
          <el-option
            v-for="region in regionList"
            :key="region.areaid"
            :label="
              region.city +
              '-' +
              region.county +
              '-' +
              region.town +
              '-' +
              region.village
            "
            :value="region.areaid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="billstate">
        <el-input
          v-model="queryParams.billstate"
          placeholder="请输入单据状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:exebill:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:exebill:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:exebill:remove']"
          >删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:exebill:export']"
          >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="exebillList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="单据编码" prop="billcode" />
      <el-table-column label="单据日期" prop="billdate" width="180" />
      <el-table-column label="司机" prop="driverid">
        <template slot-scope="scope">
          {{ driverMatching(scope.row.driverid) }}
        </template>
      </el-table-column>
      <el-table-column label="车辆" prop="tid">
        <template slot-scope="scope">
          {{ truckListMatching(scope.row.tid) }}
        </template>
      </el-table-column>
      <el-table-column label="开单人" prop="empid">
        <template slot-scope="scope">
          {{ employeeMatching(scope.row.empid) }}
        </template>
      </el-table-column>
      <el-table-column label="区域" prop="areaid">
        <template slot-scope="scope">
          {{ regionMatching(scope.row.areaid) }}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" prop="billstate" />
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:exebill:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:exebill:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改派工单主表对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <div ref="formContent">
        <el-form
          ref="form"
          id="upDate-form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据编码" prop="billcode">
                <el-input
                  v-model="form.billcode"
                  placeholder="请输入单据编码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据状态" prop="billstate">
                <el-input
                  v-model="form.billstate"
                  placeholder="请输入单据状态"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="司机" prop="driverid">
                <el-select
                  v-model="form.driverid"
                  filterable
                  placeholder="请选择司机"
                  clearable
                  size="small"
                  @change="form.tid = null"
                >
                  <el-option
                    v-for="driver in driverList"
                    :key="driver.empid"
                    :label="driver.name"
                    :value="driver.empid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆" prop="tid">
                <el-select
                  v-model="form.tid"
                  filterable
                  placeholder="请选择车辆"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="truck in truckList"
                    v-if="form.driverid == truck.driverid"
                    :key="truck.tid"
                    :label="truck.truckcode"
                    :value="truck.tid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="开单人" prop="empid">
                <el-select
                  v-model="form.empid"
                  filterable
                  placeholder="请选择开单人"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="employee in employeeList"
                    :key="employee.empid"
                    :label="employee.name"
                    :value="employee.empid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域" prop="areaid">
                <el-select
                  v-model="form.areaid"
                  filterable
                  @change="getorderList(form.areaid)"
                  placeholder="请选择区域"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="region in regionList"
                    :key="region.areaid"
                    :label="
                      region.city +
                      '-' +
                      region.county +
                      '-' +
                      region.town +
                      '-' +
                      region.village
                    "
                    :value="region.areaid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="form.remark"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="center">派工单明细信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAddLExebilldetail"
                >添加
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDeleteLExebilldetail"
                >删除
              </el-button>
            </el-col>
          </el-row>
          <el-table
            :data="lexebilldetailList"
            :key="dialogTableKey"
            :row-class-name="rowLExebilldetailIndex"
            @selection-change="handleLExebilldetailSelectionChange"
            ref="lExebilldetail"
            v-loading="tableLoading"
            style="width: 150%"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column label="序号" prop="index" width="50" />
            <el-table-column label="订单编号" prop="orderbillid">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.orderbillid"
                  filterable
                  placeholder="请选择客户"
                  clearable
                  size="small"
                  @change="orderbillidChange($event, scope.row.index)"
                >
                  <el-option
                    v-for="guest in orderList"
                    :key="guest.billid"
                    :label="guest.billcode"
                    :value="guest.billid"
                    :disabled="optionDisabled(guest)"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="客户" prop="gid">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.guestName"
                  :disabled="true"
                  placeholder="请输入客户"
                />
              </template>
            </el-table-column>
            <el-table-column label="地址" prop="address">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.address"
                  :disabled="true"
                  placeholder="请输入地址"
                />
              </template>
            </el-table-column>
            <el-table-column label="联系电话" prop="tel">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.tel"
                  :disabled="true"
                  placeholder="请输入联系电话"
                />
              </template>
            </el-table-column>
            <el-table-column label="完成标识" prop="isoverStr">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.isoverStr"
                  :disabled="true"
                  placeholder="请输入完成标识"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  :disabled="true"
                  placeholder="请输入备注"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        
        <el-button type="primary" @click="printHandle">打 印</el-button>
        <el-button @click="cancel">取 消</el-button>
        <!-- <el-button @click="print" v-print="printObj">打印</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExebill, getExebill, delExebill, addExebill, updateExebill, getCode, getOrderList, } from "@/api/system/exebill";
import { listRegionAll } from "@/api/system/region";
import { listSalesmanAll, listDriverAll } from "@/api/system/employee";
import { listTruckAll } from "@/api/system/truck";
import { listGuestAll } from "@/api/system/guest";
import html2canvas from "html2canvas";
import printJS from "print-js";
export default {
  name: "Exebill",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLExebilldetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 派工单主表表格数据
      exebillList: [],
      // 派工单明细表格数据
      lexebilldetailList: [],
      //司机列表
      driverList: [],
      //员工列表
      employeeList: [],
      //客户列表
      guestList: [],
      //区域列表
      regionList: [],
      //车辆列表
      truckList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billcode: null,
        billdate: null,
        driverid: null,
        tid: null,
        empid: null,
        areaid: null,
        billstate: null,
      },
      // 表单参数
      form: {},
      orderList: [],
      // 表单校验
      rules: {
        billcode: [
          { required: true, message: "单据编码不能为空", trigger: "blur" },
        ],
        driverid: [
          { required: true, message: "司机ID不能为空", trigger: "blur" },
        ],
        empid: [{ required: true, message: "开单人不能为空", trigger: "blur" }],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
      },
      dialogTableKey: true,
      tableLoading: false,
      printObj: {
        id: "upDate-form",
        popTitle: "",
      },
    };
  },
  created() {
    this.getList();
    this.getRegionList();
    this.getDriverList();

    this.getTruckList();
    this.getGuesList();
  },
  methods: {
    getCode() {
      getCode().then((response) => {
        this.form.billcode = response.data;
      });
    },
    getTruckList() {
      listTruckAll().then((response) => {
        this.truckList = response.data;
      });
    },
    getGuesList() {
      listGuestAll().then((response) => {
        this.guestList = response.data;
      });
    },
    //订单编号下拉框
    getorderList(value) {
      let data = {
        areaId: value,
        billid: this.form.billid,
      };
      return new Promise((resolve, reject) => {
        getOrderList(data)
          .then((response) => {
            this.orderList = response.data;
            this.lexebilldetailList = [];
            this.dialogTableKey = !this.dialogTableKey;
            resolve(1);
          })
          .catch((res) => {
            reject(0);
          });
      });
    },
    //表格订单编号的选择
    orderbillidChange(event, index) {
      let item = this.orderList.find((item) => item.billid === event);
      let { billid } = item;
      item.orderbillid = billid;
      let isoverStr = item.isover ? "已完成" : "未完成";
      item.isoverStr = isoverStr;
      this.lexebilldetailList[index - 1] = item;
      this.dialogTableKey = !this.dialogTableKey;
    },

    /** 查询派工单主表列表 */
    getList() {
      this.loading = true;
      listExebill(this.queryParams).then((response) => {
        this.exebillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRegionList() {
      listRegionAll().then((response) => {
        this.regionList = response.data;
      });
    },
    getDriverList() {
      listDriverAll().then((response) => {
        this.driverList = response.data;
        this.getSalesmanList();
      });
    },
    getSalesmanList() {
      listSalesmanAll().then((response) => {
        this.employeeList = response.data;
      });
    },
    regionMatching(areaid) {
      let name = "-";
      this.regionList.map((item) => {
        if (areaid == item.areaid) {
          name =
            item.city +
            "-" +
            item.county +
            "-" +
            item.town +
            "-" +
            item.village;
          return;
        }
      });
      return name;
    },
    employeeMatching(employeeId) {
      let name = "-";
      this.employeeList.map((item) => {
        if (employeeId == item.empid) {
          name = item.name;
          return;
        }
      });
      return name;
    },

    driverMatching(employeeId) {
      let name = "-";
      this.driverList.map((item) => {
        if (employeeId == item.empid) {
          name = item.name;
          return;
        }
      });
      return name;
    },
    truckListMatching(tid) {
      let name = "-";
      this.truckList.map((item) => {
        if (tid == item.tid) {
          name = item.truckcode;
          return;
        }
      });
      return name;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billid: null,
        billcode: null,
        billdate: null,
        driverid: null,
        tid: null,
        empid: null,
        areaid: null,
        billstate: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.lexebilldetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    printHandle() {
      const style = ['@page {margin:0;size: A4} html {margin: 4mm;}']
      html2canvas(this.$refs.formContent, {
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
      }).then((canvas) => {
        const url = canvas.toDataURL();
        this.img = url;
        printJS({
          printable: url,
          type: "image",
          style,
        });
      });
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.billid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加派工单主表";
      this.getCode();
      this.orderList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const billid = row.billid || this.ids;
      getExebill(billid).then(async (response) => {
        this.open = true;
        this.title = "修改派工单主表";
        this.tableLoading = true;
        this.form = response.data;
        let orderLoading = await this.getorderList(this.form.areaid);
        if (orderLoading) {
          //同步
          this.lexebilldetailList = response.data.lexebilldetailList;
        }

        this.tableLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.lexebilldetailList = this.lexebilldetailList;
          if (this.form.billid != null) {
            updateExebill(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExebill(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billids = row.billid || this.ids;
      this.$modal
        .confirm('是否确认删除派工单主表编号为"' + billids + '"的数据项？')
        .then(function () {
          return delExebill(billids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 派工单明细序号 */
    rowLExebilldetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 派工单明细添加按钮操作 */
    handleAddLExebilldetail() {
      let obj = {};
      obj.itemsno = "";
      obj.gid = "";
      obj.address = "";
      obj.tel = "";
      obj.isover = "";
      obj.remark = "";
      this.lexebilldetailList.push(obj);
    },
    /** 派工单明细删除按钮操作 */
    handleDeleteLExebilldetail() {
      if (this.checkedLExebilldetail.length == 0) {
        this.$modal.msgError("请先选择要删除的派工单明细数据");
      } else {
        const lexebilldetailList = this.lexebilldetailList;
        const checkedLExebilldetail = this.checkedLExebilldetail;
        this.lexebilldetailList = lexebilldetailList.filter(function (item) {
          return checkedLExebilldetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleLExebilldetailSelectionChange(selection) {
      this.checkedLExebilldetail = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/exebill/export",
        {
          ...this.queryParams,
        },
        `exebill_${new Date().getTime()}.xlsx`
      );
    },
    optionDisabled(data) {
      let b = false;
      this.lexebilldetailList.forEach((i) => {
        if (i.orderbillid == data.billid) {
          b = true;
          return b;
        }
      });
      return b;
    },
  },
};
</script>

